package juc;

import java.util.concurrent.CountDownLatch;

class MyRunnable2 implements Runnable{//一个耗时的线程

    private CountDownLatch latch;

    public MyRunnable2(CountDownLatch latch){
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            for (int i=0;i<10000;i++){
                if (i%2 ==0){
                    System.out.print(i);
                }
            }
        }finally {
            latch.countDown();//闭锁计数器-1
        }
    }
}

public class MyCountDownLatch {
    public static void main(String[] args) {

        //创建一个闭锁，10个计数器
        CountDownLatch latch = new CountDownLatch(10);

        MyRunnable2 myRunnable2 = new MyRunnable2(latch);

        long startTime = System.currentTimeMillis();

        //并发10个线程
        for(int i=0;i<10;i++){
            new Thread(myRunnable2).start();
        }

        //等待闭锁
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();
        System.out.println();
        System.out.println("耗时："+(endTime-startTime));
    }
}
